#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

const std::string gpipeFile = "./fifo";
const mode_t gmode = 0600; 
const int gdefaultfd = -1;
const int gsize = 1024;
const int gForRead = O_RDONLY;
const int gForWrite = O_WRONLY;

class Fifo
{
private:
int OpenPipe(int flag)
{
    //打开管道
    int fd = ::open(gpipeFile.c_str(), flag);
    if (fd < 0)
    {
        std::cerr << "open error" << std::endl; 
    }
    std::cout << "open suceess" << std::endl; 
    return fd;
}
public:
    Fifo(): _fd(-1){
        int n = ::mkfifo(gpipeFile.c_str(),gmode);
        if(n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo sucess" << std::endl;
        // sleep(10);
    }
     bool OpenPipeForRead()
    {
        _fd = OpenPipe(gForRead);
        if(_fd < 0)
        {
            return false;
        }
        return true;
    }
    bool OpenPipeForWrite()
    {
        _fd = OpenPipe(gForWrite);
        if(_fd < 0)
        {
            return false;
        }
        return true;
    }
    int Wait()
    {
        //等待write写入到管道中。
        int code = 0;
        ssize_t n = ::read(_fd,&code,sizeof(code));
        if(n==sizeof(code))
        {
            return 0;
        }
        else if(n == 0)
        {
            return 1;
        }
        else{
            return 2;
        }
    }
    void Signal(){   //写入信号，表示数据已经被写入
         int code = 1;
        ::write(_fd, &code, sizeof(code));
    }
    ~Fifo()
    {
         if(_fd >= 0)
        {
            ::close(_fd);
        }
        int n = ::unlink(gpipeFile.c_str());
        if(n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink sucess" << std::endl;
    }
private:
    int _fd;
};

Fifo gpipe;